package com.swiftops.common.service.impl;

import com.alibaba.fastjson.JSON;
import com.swiftops.common.service.TokenService;
import com.swiftops.common.model.TokenModel;
import com.swiftops.common.model.User;
import com.swiftops.common.util.IdGen;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.JwtException;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.time.DateUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.util.Date;

@Slf4j
//@Component
public class TokenServiceImpl implements TokenService {

    @Value("${app.jwtSecret:mySecret}")
    private String jwtSecret;
    @Value("${app.jwtExpirationInMinutes:120}") // 设置默认值为120分钟
    private int jwtExpirationInMinutes;

    @Override
    public TokenModel createToken(User user) {
        //使用转换后的分钟数计算过期时间
        Date expiryDate = DateUtils.addMinutes(new Date(), jwtExpirationInMinutes);
        String tokenId = String.format("token_%s_%s", user.getUsername(), IdGen.next());
        String token = Jwts.builder()
                .setId(tokenId)
                .setSubject(user.getUserId())//主题
                .claim("user", user)
                .setIssuedAt(new Date())//签发时间
                .setExpiration(expiryDate)//失效时间
                .signWith(SignatureAlgorithm.HS512, jwtSecret)
                .compact();
        TokenModel model = new TokenModel(token, "", user);
        model.setTokenId(tokenId);
        model.setExpiryTime(expiryDate.getTime());
        return model;
    }

    @Override
    public TokenModel refreshToken(String refreshToken) {
        return null;
    }

    @Override
    public boolean checkToken(TokenModel model) {
        if (model == null) return false;
        String token = model.getToken();
        if (StringUtils.isBlank(token)) return false;
        // 验证JWT Token
        try {
            Jwts.parser().setSigningKey(jwtSecret).parseClaimsJws(token);
            // Token is valid
            return true;
        } catch (JwtException e) {
            // Token is invalid
            log.error("Invalid JWT signature");
        }
        return false;
    }

    @Override
    public TokenModel getTokenModel(String token) {
        if (StringUtils.isBlank(token)) return null;

        Claims claims = Jwts.parser().setSigningKey(jwtSecret).parseClaimsJws(token).getBody();
        String tokenId = claims.getId();
        //String subject = claims.getSubject();//用户ID
        Object object = claims.get("user");
        User user = JSON.parseObject(JSON.toJSONString(object), User.class);
        //
        TokenModel model = new TokenModel();
        model.setTokenId(tokenId);
        model.setUser(user);
        model.setToken(token);
        //
        return model;
    }

    @Override
    public boolean deleteToken(String token) {
        return false;
    }
}
